package com.cgy.utils.spider.spider;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.management.JMException;

import org.apache.commons.lang3.StringUtils;

import com.cgy.utils.spider.callback.AbstractCallBack;
import com.cgy.utils.spider.handler.Downloads;
import com.cgy.utils.spider.pipeline.ConsolePipeline;
import com.cgy.utils.spider.template.Field;
import com.cgy.utils.spider.template.Template;
import com.google.common.collect.Lists;

import lombok.extern.slf4j.Slf4j;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.monitor.SpiderMonitor;
import us.codecraft.webmagic.pipeline.JsonFilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;

/**
 * @author CHTK
 */
@Slf4j
public class WebMagicSpider extends AbstractSpider implements PageProcessor {

    private String type;
    private Spider spider;
    private String deep;
    private List<String> url = Lists.newArrayList();
    private ConcurrentMap<String, Object> cache = new ConcurrentHashMap<>();


    @Override
    public void process(Page page) {
        String name, regex;
        String download;
        List<String> all = null;

        if (setting.fullPage()) {
            cache.put("page", page.getRawText());
        }

        for (Template template1 : template) {
            List<Field> fields = template1.getFields();
            for (Field field : fields) {
                type = field.getType();
                name = field.getName();
                regex = field.getRegex();
                download = field.getDownload();
                if ("url".equals(type)) {
                    all = page.getHtml().regex(regex).all();
                } else if ("html".equals(type)) {
                    all = page.getHtml().xpath(regex).all();
                }
                cache.put(name, all);
                page.putField(name, all);

                if(StringUtils.isNotBlank(download)) {
                    Downloads.loader(all, download);
                }
            }
        }

        if (null != this.abstractCallBack) {
            this.abstractCallBack.callback(cache);
        }

        if (setting.isDeep()) {
            if (StringUtils.isNotBlank(deep)) {
                if ("all".equals(deep)) {
                    all = page.getHtml().xpath("//a/@href").all();
                } else {
                    all = page.getHtml().links().regex(deep).all();
                }
                url.addAll(all);
                log.debug("href:{}", all);
                page.addTargetRequests(all);
            }
        }
    }

    @Override
    public Site getSite() {
        Site me = Site.me();
        if (StringUtils.isNotBlank(setting.charset())) {
            me.setCharset(setting.charset());
        }

        if (setting.sleepTime() > 0L) {
            me.setSleepTime(setting.sleepTime());
        }
        if (setting.cycleRetryTime() > 0L) {
            me.setCycleRetryTimes(setting.cycleRetryTime());
        }
        if (setting.timeout() > 0) {
            me.setTimeOut(setting.timeout());
        }
        if (setting.retryTime() > 0) {
            me.setRetryTimes(setting.retryTime());
        }

        return me;
    }


    @Override
    public void start(AbstractCallBack abstractCallBack) {
        if (null == template || template.isEmpty()) {
            log.error("template does not null");
            return;
        }
        Template first = template.get(0);
        this.deep = first.getDeepRegex();

        this.spider = Spider.create(this);
        for (Template template1 : template) {
            this.spider.addUrl(template1.getUrl());
        }
        this.spider.setUUID(UUID.randomUUID().toString())
                .thread(Integer.valueOf(first.getThread()));
        if (StringUtils.isNotBlank(setting.download())) {
            this.spider.addPipeline(new JsonFilePipeline(setting.download()));
        }
        if (setting.console()) {
            this.spider.addPipeline(new ConsolePipeline());
        }

        if (null != setting.downloader()) {
            this.spider.setDownloader(setting.downloader());
        }
        try {
            SpiderMonitor.instance().register(this.spider);
        } catch (JMException e) {

        }

        this.abstractCallBack = abstractCallBack;
        if (setting.async()) {
            spider.runAsync();
        } else {
            spider.run();
        }
    }

    @Override
    public void start() {
        start(null);
    }

    @Override
    public void stop() {
        this.spider.stop();
    }

    public static AbstractSpider build() {
        return new WebMagicSpider();
    }
}
